package com.yxw.webview01;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpThread extends Thread {

    private String mUrl;

    public HttpThread(String url) {
        this.mUrl = url;
    }

    @Override
    public void run() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            URL httpUrl = new URL(mUrl);
            URLConnection connection = httpUrl.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);


            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File downloadFile = Environment.getDownloadCacheDirectory();
                File sdFile = new File(downloadFile, "test.apk");
                fos = new FileOutputStream(sdFile);
                fis = new FileInputStream(downloadFile);
            }

            byte[] bytes = new byte[6 * 1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                if (fos != null) {
                    fos.write(bytes,0, len);

                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try{
                if(fos!=null){
                    fos.close();
                }
                if(fis!=null){
                    fis.close();
                }
            }catch(Exception e){
                e.printStackTrace();
            }

        }

    }
}
